import {Injectable} from '@angular/core';
import {Events, Platform} from "ionic-angular";
import {BaiduProvider} from "@providers/interface/baidu";

declare let cordova;

/*
  语音识别

  Generated class for the AiProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class AiProvider {

  isApp: boolean = false;

  constructor(private platform: Platform,
              private baidu: BaiduProvider,
              private events: Events) {

    this.platform.ready().then(() => {
      this.isApp = this.platform.is('cordova');
      if (this.isApp) {
        cordova.plugins.bdasr.addEventListener(res => {
          this.events.publish(res.type, res);
        }, err => {
          this.events.publish(err.type, err);
        });
      }
    });
  }

  start() {
    cordova.plugins.bdasr.startSpeechRecognize();
  }

  stop() {
    cordova.plugins.bdasr.startSpeechRecognize();
  }

  text2audio(text) {
    this.baidu.text2audio(text).then(v => {
      let audio = document.createElement('audio');
      audio.setAttribute('autoplay', 'autoplay');
      audio.style.display = 'none';
      audio.setAttribute('src', URL.createObjectURL(v));
    });
  }
}
